package com.fkcai.hansoul.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.transaction.support.TransactionTemplate;

import javax.sql.DataSource;

@Configuration
@EnableTransactionManagement
public class TransactionConfig {
	
	/**
	 * 配置事务管理器
	 * @param dataSource 数据源
	 */
	@Bean
	public PlatformTransactionManager transactionManager(DataSource dataSource) {
		DataSourceTransactionManager transactionManager = new DataSourceTransactionManager();
		
		transactionManager.setDataSource(dataSource);
		transactionManager.setDefaultTimeout(30);   // 默认事务超时时间为 30 秒
		transactionManager.setNestedTransactionAllowed(true);   // 允许嵌套事务
		
		return transactionManager;
	}
	
	/**
	 * 配置事务模板
	 * @param transactionManager 事务管理器
	 */
	@Bean
	public TransactionTemplate transactionTemplate(PlatformTransactionManager transactionManager) {
		TransactionTemplate template = new TransactionTemplate(transactionManager);
		template.setTimeout(30); // 编程式事务超时
		return template;
	}
}
